import axios from "axios";
import type { InternalAxiosRequestConfig } from "axios";
import EventEmitTool from "../tools/event-emit.tool";
import { UtilTool, CryptoTool } from "@webxue/common";

export const useAxios = (options: UseAxiosOptions) => {
  const request = axios.create({
    baseURL: options.baseURL,
    timeout: options.timeout || 5000
  });

  // 添加请求拦截器
  request.interceptors.request.use(
    async function (config:CusRequestConfig<InternalAxiosRequestConfig>) {
      if (options.getConfig) {
        config = options.getConfig(config);
      }
      // 内置处理
      const requestType = config.requestType?.split("_") || [];
      if(requestType.includes("noToken")) {
        // 传有noToken，根据加密盐和时间戳生成签名，服务端验签通过跳过鉴权拦截
        const authSalt = await options.getSalt?.();
        if(authSalt) {
          const timestamp = UtilTool.dayjs().valueOf();
          const cryptoJs = CryptoTool.cryptoJs;
          config.headers["x-auth-pass-signture"] = cryptoJs.SHA256(timestamp + authSalt).toString(cryptoJs.enc.Hex);
          config.headers["x-auth-pass-timestamp"] = timestamp;
        }
      }

      return config;
    },
    function (error) {
      return Promise.reject(error);
    }
  );

  // 添加响应拦截器
  request.interceptors.response.use(
    function (response) {
      if (response.status === 200 || response.status === 201) {
        if (options.onSuccess) options.onSuccess(response.data);
        // find接口请求成功，但data无数据，表示数据已被删除，需跳转到404
        if(!response.data.data && response.config.url?.endsWith("/find")) {
          EventEmitTool.emit("API:FIND:NOT_FUND");
        } else {
          return response.data;
        }
      } else if (response.status === 401) {
        EventEmitTool.emit("API:UN_AUTH");
      }
      return response;
    },
    function (error) {
      if (error.response.status === 401) {
        EventEmitTool.emit("API:UN_AUTH");
      }
      return Promise.reject(error);
    }
  );

  return request;
};

// 定义请求参数类型
export declare interface UseAxiosOptions {
  // 服务地址
  baseURL?: string;
  // 超时时间（毫秒）
  timeout?: number;
  // 获取请求拦截的config
  getConfig?: (config: InternalAxiosRequestConfig) => InternalAxiosRequestConfig;
  // 获取不需要鉴权的加密盐
  getSalt?:() => Promise<string>;
  // 响应成功回调
  onSuccess?: (data: ResponseData) => void;
}
